package com.ds.rad.service;

import com.ds.annotation.MethodChinaName;
import com.ds.common.JDSException;
import com.ds.config.ErrorResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.esd.engine.ESDClient;
import com.ds.esd.engine.ESDFacrory;
import com.ds.esd.engine.ProjectVersion;
import com.ds.esd.engine.enums.ProjectTempType;
import com.ds.esd.manager.temp.ProjectTemp;
import com.ds.rad.bean.XUIFile;
import com.ds.rad.bean.XUIModule;
import com.ds.vfs.FileInfo;
import com.ds.vfs.Folder;
import com.ds.vfs.VFSConstants;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.vfs.ct.CtVfsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping(value = {"/admin/temp/"})
@MethodChinaName(cname = "RAD编辑器管理")
public class ProjectTempServcie {


    @MethodChinaName(cname = "获取工程分类")
    @RequestMapping(value = {"getTempType"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<ProjectTemp>> getTempType(String path, String pattern) {
        ListResultModel<List<ProjectTemp>> result = new ListResultModel<List<ProjectTemp>>();
        List<ProjectTemp> temps = new ArrayList<>();
        for (ProjectTempType type : ProjectTempType.values()) {
            ProjectTemp temp = new ProjectTemp(type);
            temps.add(temp);
        }
        result.setData(temps);

        return result;
    }


    @MethodChinaName(cname = "获取页面模板")
    @RequestMapping(value = {"getTempPage"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIModule> getTempPage(String path, String pattern) {
        ResultModel<XUIModule> result = new ResultModel<XUIModule>();
        XUIModule xuiModule = new XUIModule();
        List<XUIFile> modules = xuiModule.getFiles();

        Folder folder = null;
        try {
            ProjectVersion version = getClient().getProjectVersionByName(path);
            folder = getVfsClient().getFolderByPath(path);
            if (folder != null) {
                List<Folder> infos = folder.getChildrenRecursivelyList();
                for (Folder cfolder : infos) {
                    List<FileInfo> fileInfos = cfolder.getFileList();
                    boolean isProject = false;
                    for (FileInfo fileInfo : fileInfos) {
                        if (fileInfo.getName().equals("xuiconf.js")) {
                            isProject = true;
                        }
                    }
                    if (isProject) {
                        if (pattern != null && !pattern.equals("")) {
                            Pattern p = Pattern.compile(pattern);
                            Matcher matcher = p.matcher(cfolder.getName());
                            if (matcher.find()) {
                                modules.add(new XUIFile(cfolder, version));
                            }
                        } else {
                            modules.add(new XUIFile(cfolder, version));
                        }
                    }

                }

            }


            result.setData(xuiModule);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取工程数据")
    @RequestMapping(value = {"getAllSystemProject"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIModule> getAllSystemProject(String path, String pattern) {
        ResultModel<XUIModule> result = new ResultModel<XUIModule>();
        XUIModule xuiModule = new XUIModule();
        List<XUIFile> modules = xuiModule.getFiles();

        Folder folder = null;
        try {
            ProjectVersion version = getClient().getProjectVersionByName(path);
            folder = getVfsClient().getFolderByPath(path);
            if (folder != null) {
                List<Folder> infos = folder.getChildrenRecursivelyList();

                for (Folder cfolder : infos) {
                    List<FileInfo> fileInfos = cfolder.getFileList();
                    boolean isProject = false;
                    for (FileInfo fileInfo : fileInfos) {
                        if (fileInfo.getName().equals("xuiconf.js")) {
                            isProject = true;
                        }
                    }
                    if (isProject) {
                        if (pattern != null && !pattern.equals("")) {
                            Pattern p = Pattern.compile(pattern);
                            Matcher matcher = p.matcher(cfolder.getName());
                            if (matcher.find()) {
                                modules.add(new XUIFile(cfolder, version));
                            }
                        } else {
                            modules.add(new XUIFile(cfolder, version));
                        }
                    }

                }

            }


            result.setData(xuiModule);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());

        }
        return result;
    }


    @MethodChinaName(cname = "获取所有模板工程")
    @RequestMapping(value = {"getProjectTemp"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIModule> getProjectTemp(String path) {
        ResultModel<XUIModule> result = new ResultModel<XUIModule>();
        XUIModule xuiModule = new XUIModule();
        List<XUIFile> modules = xuiModule.getFiles();

        Folder folder = null;
        try {
            folder = getVfsClient().getFolderByPath(path);
            ProjectVersion version = getClient().getProjectVersionByName(path);
            // ProjectVersion version = ProjectFactory.getInstance().getProjectVersionByName(path);


            if (folder != null) {
                List<Folder> folders = folder.getChildrenList();
                for (Folder cfolder : folders) {
                    modules.add(new XUIFile(cfolder, version));
                }
                FileInfo fileInfo = getVfsClient().getFileByPath(folder.getPath() + "config.json");
                if (fileInfo != null) {
                    xuiModule.setConf(this.readFile(fileInfo.getPath()));
                }
            }

            result.setData(xuiModule);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }

        return result;
    }


    @RequestMapping(value = {"adminManager"}, method = {RequestMethod.GET})
    public void adminManager(HttpServletResponse response) {
        InputStream stream = null;
        FileInfo fileInfo = null;
        try {
            fileInfo = this.getVfsClient().getFileByPath("system/adminManager.html");
            if (fileInfo != null) {
                stream = fileInfo.getCurrentVersonInputStream();
            }
            OutputStream os = response.getOutputStream();
            // 循环写入输出流
            byte[] b = new byte[4096];
            int length;
            while ((length = stream.read(b)) > 0) {
                os.write(b, 0, length);

            }
            try {
                os.close();
                stream.close();
            } catch (final IOException ioe) {
            }

        } catch (JDSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    private String readFile(String path) {
        String json = "{}";

        try {
            json = getVfsClient().readFileAsString(path, VFSConstants.Default_Encoding).toString();
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return json;
    }

    public ESDClient getClient() throws JDSException {

        ESDClient client = ESDFacrory.getAdminESDClient();

        return client;
    }


    public CtVfsService getVfsClient() {

        CtVfsService vfsClient = CtVfsFactory.getCtVfsService();
        return vfsClient;
    }
}
